package org.umss.fixture.activities;

import java.util.ArrayList;
import java.util.List;

import org.umss.fixture.R;
import org.umss.fixture.model.TeamPosition;
import org.umss.fixture.services.FixtureBuilderServices;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class ScoreBoardActivity extends Activity {

    private TableLayout positionsTable;
    private List<TeamPosition> positions;
    private static ProgressDialog progressDialog;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_board);
        positionsTable = (TableLayout) findViewById(R.id.scoreboard_table);
        positions = new ArrayList<TeamPosition>();
        Bundle bundle = getIntent().getExtras();
        String championshipName = bundle.getString("CHAMPIONSHIP_NAME");
        new LoadScoreBoardTask().execute(championshipName);
    }

    private void loadData() {
        for (TeamPosition team : positions) {
            TableRow row = (TableRow) LayoutInflater.from(ScoreBoardActivity.this).inflate(
                    R.layout.team_row, null);
            ((TextView) row.findViewById(R.id.teamName)).setText(team.getTeamName());
            ((TextView) row.findViewById(R.id.wins)).setText(team.getWinGames() + "");
            ((TextView) row.findViewById(R.id.losts)).setText(team.getLostGames() + "");
            ((TextView) row.findViewById(R.id.draws)).setText(team.getDrawGames() + "");
            ((TextView) row.findViewById(R.id.points)).setText(team.getPoints() + "");
            positionsTable.addView(row);
        }
    }

    private class LoadScoreBoardTask extends AsyncTask<String, Void, Void> {

        @Override
        public void onPreExecute() {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(ScoreBoardActivity.this);
                progressDialog.setIndeterminate(true);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Retrieving scoreboard...");
                progressDialog.show();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            String championshipName = params[0];
            FixtureBuilderServices fixtureBuilderServices = new FixtureBuilderServices();
            positions = fixtureBuilderServices
                    .getScoreBoard(championshipName);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            loadData();
            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            progressDialog = null;
        }
    }
    
}
